<template>
  <div class="settings-page">
    <AppHeader />
    <div class="settings-container">
      <AppSidebar />
      <div class="settings-content">
        <h1>设置</h1>
        
        <el-tabs v-model="activeTab" tab-position="left">
          <!-- 常规设置 -->
          <el-tab-pane label="常规" name="general">
            <el-card shadow="never">
              <template #header>
                <div class="card-header">
                  <span>常规设置</span>
                </div>
              </template>
              
              <div class="settings-section">
                <!-- 主题设置 -->
                <div class="setting-item">
                  <label>主题：</label>
                  <el-radio-group v-model="theme" @change="handleThemeChange">
                    <el-radio label="light">浅色</el-radio>
                    <el-radio label="dark">深色</el-radio>
                    <el-radio label="auto">跟随系统</el-radio>
                  </el-radio-group>
                </div>
                
                <!-- 语言设置 -->
                <div class="setting-item">
                  <label>语言：</label>
                  <el-select v-model="language" @change="handleLanguageChange">
                    <el-option label="简体中文" value="zh-CN" />
                    <el-option label="English" value="en-US" />
                  </el-select>
                </div>
                
                <!-- 自动启动 -->
                <div class="setting-item">
                  <label>开机自启动：</label>
                  <el-switch 
                    v-model="autoStart" 
                    @change="handleAutoStartChange"
                  />
                </div>
              </div>
            </el-card>
          </el-tab-pane>
          
          <!-- 照片设置 -->
          <el-tab-pane label="照片" name="photos">
            <el-card shadow="never">
              <template #header>
                <div class="card-header">
                  <span>照片设置</span>
                </div>
              </template>
              
              <div class="settings-section">
                <!-- 默认视图模式 -->
                <div class="setting-item">
                  <label>默认视图模式：</label>
                  <el-radio-group v-model="defaultViewMode" @change="handleViewModeChange">
                    <el-radio label="grid">网格视图</el-radio>
                    <el-radio label="list">列表视图</el-radio>
                  </el-radio-group>
                </div>
                
                <!-- 网格列数 -->
                <div class="setting-item">
                  <label>网格列数：</label>
                  <el-slider
                    v-model="gridColumns"
                    :min="3"
                    :max="10"
                    :step="1"
                    show-stops
                    @change="handleGridColumnsChange"
                  />
                </div>
                
                <!-- 缩略图质量 -->
                <div class="setting-item">
                  <label>缩略图质量：</label>
                  <el-select v-model="thumbnailQuality" @change="handleThumbnailQualityChange">
                    <el-option label="低" value="low" />
                    <el-option label="中" value="medium" />
                    <el-option label="高" value="high" />
                  </el-select>
                </div>
                
                <!-- 自动导入 -->
                <div class="setting-item">
                  <label>自动导入文件夹：</label>
                  <el-switch 
                    v-model="autoImport" 
                    @change="handleAutoImportChange"
                  />
                  <div v-if="autoImport" class="setting-subitem">
                    <el-button @click="selectImportFolder">选择文件夹</el-button>
                    <span v-if="importFolder" class="folder-path">{{ importFolder }}</span>
                  </div>
                </div>
              </div>
            </el-card>
          </el-tab-pane>
          
          <!-- 数据库设置 -->
          <el-tab-pane label="数据库" name="database">
            <el-card shadow="never">
              <template #header>
                <div class="card-header">
                  <span>数据库设置</span>
                </div>
              </template>
              
              <div class="settings-section">
                <!-- 数据库路径 -->
                <div class="setting-item">
                  <label>数据库路径：</label>
                  <div class="database-path">
                    <span>{{ dbPath }}</span>
                    <el-button @click="showDbInFolder" size="small">在文件夹中显示</el-button>
                  </div>
                </div>
                
                <!-- 数据库大小 -->
                <div class="setting-item">
                  <label>数据库大小：</label>
                  <span>{{ dbSize }}</span>
                </div>
                
                <!-- 数据库操作 -->
                <div class="setting-item">
                  <label>数据库操作：</label>
                  <div class="database-actions">
                    <el-button @click="optimizeDatabase" :loading="dbOptimizing">
                      优化数据库
                    </el-button>
                    <el-button @click="vacuumDatabase" :loading="dbVacuuming">
                      清理数据库
                    </el-button>
                    <el-button type="danger" @click="confirmResetDatabase">
                      重置数据库
                    </el-button>
                  </div>
                </div>
              </div>
            </el-card>
          </el-tab-pane>
          
          <!-- 关于 -->
          <el-tab-pane label="关于" name="about">
            <el-card shadow="never">
              <template #header>
                <div class="card-header">
                  <span>关于应用</span>
                </div>
              </template>
              
              <div class="about-section">
                <div class="app-info">
                  <div class="app-logo">
                    <img src="/icons/icon.png" alt="应用图标" />
                  </div>
                  <h2>Photo Plover Store</h2>
                  <p>版本 {{ appVersion }}</p>
                  <p>一个本地照片管理应用，类似谷歌相册</p>
                </div>
                
                <div class="tech-info">
                  <h3>技术栈</h3>
                  <ul>
                    <li>Electron + Vue 3 + TypeScript</li>
                    <li>Element Plus UI 组件库</li>
                    <li>SQLite 本地数据库</li>
                    <li>Sharp 图片处理</li>
                  </ul>
                </div>
                
                <div class="links">
                  <h3>相关链接</h3>
                  <div class="link-buttons">
                    <el-button @click="openGitHub" type="primary">
                      GitHub 仓库
                    </el-button>
                    <el-button @click="checkForUpdates">
                      检查更新
                    </el-button>
                  </div>
                </div>
              </div>
            </el-card>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAppStore } from '../stores/app'
import SystemService from '../services/systemService'
import AppHeader from '../components/common/AppHeader.vue'
import AppSidebar from '../components/common/AppSidebar.vue'

const appStore = useAppStore()

// 状态
const activeTab = ref('general')
const theme = ref(appStore.theme)
const language = ref(appStore.language)
const autoStart = ref(false)
const defaultViewMode = ref(appStore.photoViewMode)
const gridColumns = ref(appStore.gridColumns)
const thumbnailQuality = ref('medium')
const autoImport = ref(false)
const importFolder = ref('')
const dbPath = ref('')
const dbSize = ref('')
const dbOptimizing = ref(false)
const dbVacuuming = ref(false)
const appVersion = ref('1.0.0')

// 生命周期钩子
onMounted(async () => {
  // 设置当前页面
  appStore.setCurrentPage('settings')
  
  // 加载设置
  await loadSettings()
  
  // 获取应用版本
  await getAppVersion()
  
  // 获取数据库信息
  await getDatabaseInfo()
})

// 加载设置
const loadSettings = async () => {
  try {
    const settings = await SystemService.getSettings()
    theme.value = settings.theme || 'light'
    language.value = settings.language || 'zh-CN'
    autoStart.value = settings.autoStart || false
    defaultViewMode.value = settings.defaultViewMode || 'grid'
    gridColumns.value = settings.gridColumns || 4
    thumbnailQuality.value = settings.thumbnailQuality || 'medium'
    autoImport.value = settings.autoImport || false
    importFolder.value = settings.importFolder || ''
  } catch (error) {
    console.error('加载设置失败:', error)
    ElMessage.error('加载设置失败')
  }
}

// 获取应用版本
const getAppVersion = async () => {
  try {
    appVersion.value = await SystemService.getAppVersion()
  } catch (error) {
    console.error('获取应用版本失败:', error)
  }
}

// 获取数据库信息
const getDatabaseInfo = async () => {
  try {
    const info = await SystemService.getDatabaseInfo()
    dbPath.value = info.path
    dbSize.value = info.size
  } catch (error) {
    console.error('获取数据库信息失败:', error)
  }
}

// 主题变更处理
const handleThemeChange = async (value: string) => {
  try {
    // 保存设置
    const settings = await SystemService.getSettings()
    settings.theme = value
    await SystemService.saveSettings(settings)
    ElMessage.success('主题设置已更新')
  } catch (error) {
    console.error('设置主题失败:', error)
    ElMessage.error('设置主题失败')
  }
}

// 语言变更处理
const handleLanguageChange = async (value: string) => {
  try {
    // 保存设置
    const settings = await SystemService.getSettings()
    settings.language = value
    await SystemService.saveSettings(settings)
    ElMessage.success('语言设置已更新')
  } catch (error) {
    console.error('设置语言失败:', error)
    ElMessage.error('设置语言失败')
  }
}

// 自动启动变更处理
const handleAutoStartChange = async (value: boolean) => {
  try {
    await SystemService.setAutoStart(value)
    ElMessage.success(`开机自启动已${value ? '开启' : '关闭'}`)
  } catch (error) {
    console.error('设置自动启动失败:', error)
    ElMessage.error('设置自动启动失败')
    // 恢复原始状态
    autoStart.value = !value
  }
}

// 视图模式变更处理
const handleViewModeChange = async (value: string) => {
  try {
    // 保存设置
    const settings = await SystemService.getSettings()
    settings.defaultViewMode = value
    await SystemService.saveSettings(settings)
    
    // 更新store
    appStore.setPhotoViewMode(value as any)
    ElMessage.success('默认视图模式已更新')
  } catch (error) {
    console.error('设置默认视图失败:', error)
    ElMessage.error('设置默认视图失败')
  }
}

// 网格列数变更处理
const handleGridColumnsChange = async (value: number) => {
  try {
    // 保存设置
    const settings = await SystemService.getSettings()
    settings.gridColumns = value
    await SystemService.saveSettings(settings)
    
    // 更新store
    appStore.setGridColumns(value)
    ElMessage.success('网格列数已更新')
  } catch (error) {
    console.error('设置网格列数失败:', error)
    ElMessage.error('设置网格列数失败')
  }
}

// 缩略图质量变更处理
const handleThumbnailQualityChange = async (value: string) => {
  try {
    // 保存设置
    const settings = await SystemService.getSettings()
    settings.thumbnailQuality = value
    await SystemService.saveSettings(settings)
    ElMessage.success('缩略图质量已更新')
  } catch (error) {
    console.error('设置缩略图质量失败:', error)
    ElMessage.error('设置缩略图质量失败')
  }
}

// 自动导入变更处理
const handleAutoImportChange = async (value: boolean) => {
  try {
    await SystemService.setAutoImportFolder(importFolder.value || '')
    ElMessage.success(`自动导入已${value ? '开启' : '关闭'}`)
  } catch (error) {
    console.error('设置自动导入失败:', error)
    ElMessage.error('设置自动导入失败')
    // 恢复原始状态
    autoImport.value = !value
  }
}

// 选择导入文件夹
const selectImportFolder = async () => {
  try {
    const folderPath = await SystemService.selectFolder()
    if (folderPath) {
      importFolder.value = folderPath
      if (autoImport.value) {
        await SystemService.setAutoImportFolder(folderPath)
      }
      ElMessage.success('导入文件夹已设置')
    }
  } catch (error) {
    console.error('选择导入文件夹失败:', error)
    ElMessage.error('选择导入文件夹失败')
  }
}

// 在文件夹中显示数据库
const showDbInFolder = async () => {
  try {
    // 这里应该调用在文件夹中显示的API
    ElMessage.success('已在文件夹中显示数据库')
  } catch (error) {
    console.error('在文件夹中显示失败:', error)
    ElMessage.error('在文件夹中显示失败')
  }
}

// 优化数据库
const optimizeDatabase = async () => {
  dbOptimizing.value = true
  
  try {
    await SystemService.optimizeDatabase()
    ElMessage.success('数据库优化完成')
    
    // 重新获取数据库信息
    await getDatabaseInfo()
  } catch (error) {
    console.error('优化数据库失败:', error)
    ElMessage.error('优化数据库失败')
  } finally {
    dbOptimizing.value = false
  }
}

// 清理数据库
const vacuumDatabase = async () => {
  dbVacuuming.value = true
  
  try {
    ElMessage.info('正在清理数据库...')
    await SystemService.cleanDatabase()
    ElMessage.success('数据库清理完成')
    
    // 重新获取数据库信息
    await getDatabaseInfo()
  } catch (error) {
    console.error('清理数据库失败:', error)
    ElMessage.error('清理数据库失败')
  } finally {
    dbVacuuming.value = false
  }
}

// 确认重置数据库
const confirmResetDatabase = async () => {
  try {
    await ElMessageBox.confirm(
      '重置数据库将删除所有照片元数据、相册和标签信息，此操作不可恢复。确定要继续吗？',
      '重置数据库',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    // 用户确认，执行重置
    await resetDatabase()
  } catch {
    // 用户取消
    ElMessage.info('已取消重置数据库')
  }
}

// 重置数据库
const resetDatabase = async () => {
  try {
    ElMessage.info('正在重置数据库...')
    await SystemService.resetDatabase()
    ElMessage.success('数据库重置完成，请重启应用')
    getDatabaseInfo() // 刷新数据库信息
  } catch (error) {
    console.error('重置数据库失败:', error)
    ElMessage.error('重置数据库失败')
  }
}

// 打开GitHub仓库
const openGitHub = () => {
  window.open('https://github.com/your-username/photo-plover-store', '_blank')
}

// 检查更新
const checkForUpdates = async () => {
  try {
    ElMessage.info('正在检查更新...')
    const updateInfo = await SystemService.checkForUpdates()
    
    if (updateInfo.hasUpdate) {
      ElMessage.success(`发现新版本: ${updateInfo.version}`)
    } else {
      ElMessage.info('当前已是最新版本')
    }
  } catch (error) {
    console.error('检查更新失败:', error)
    ElMessage.error('检查更新失败')
  }
}
</script>

<style scoped>
.settings-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.settings-container {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.settings-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background-color: var(--el-bg-color-page);
}

.settings-content h1 {
  margin-bottom: 20px;
}

.settings-section {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.setting-item {
  display: flex;
  align-items: center;
  gap: 16px;
}

.setting-item label {
  font-weight: 500;
  min-width: 120px;
  flex-shrink: 0;
}

.setting-subitem {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 8px;
  margin-left: 136px;
}

.folder-path {
  color: var(--el-text-color-regular);
  font-size: 14px;
}

/* 数据库设置样式 */
.database-path {
  display: flex;
  align-items: center;
  gap: 8px;
}

.database-actions {
  display: flex;
  gap: 8px;
}

/* 关于页面样式 */
.about-section {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.app-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  text-align: center;
}

.app-logo img {
  width: 80px;
  height: 80px;
}

.app-info h2 {
  margin: 0;
}

.app-info p {
  margin: 0;
  color: var(--el-text-color-regular);
}

.tech-info h3 {
  margin-bottom: 12px;
}

.tech-info ul {
  margin: 0;
  padding-left: 20px;
}

.tech-info li {
  margin-bottom: 8px;
}

.links h3 {
  margin-bottom: 12px;
}

.link-buttons {
  display: flex;
  gap: 12px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .setting-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .setting-subitem {
    margin-left: 0;
  }
  
  .database-path {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .database-actions {
    flex-wrap: wrap;
  }
  
  .link-buttons {
    flex-direction: column;
  }
}
</style>